import sys

import pygame
from bullet import Bullet
from alien import Alien
from time import sleep


def check_event(ai_settings, screen, ship, bullets, play_button, stats, aliens, score_board):
    """响应键盘和鼠标"""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event, ai_settings, screen, ship, bullets)
        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = pygame.mouse.get_pos()
            check_mouse_events(stats, play_button, mouse_x, mouse_y, bullets, ship, ai_settings, screen, aliens,
                               score_board)


def check_mouse_events(stats, play_button, mouse_x, mouse_y, bullets, ship, ai_settings, screen, aliens, score_board):
    """单击Play 按钮，开始游戏"""
    button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y)
    if button_clicked and not stats.game_active:
        # 重置游戏统计信息
        stats.reset_stats()
        stats.game_active = True
        # 清空外星人列表和子弹列表
        aliens.empty()
        bullets.empty()
        # 创建一群新的外星人，并让飞船居中
        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()

        # 重置游戏设置
        ai_settings.initialize_dynamic_settings()

        # 重置计分牌
        score_board.prep_score()
        #score_board.prep_high_score()
        score_board.prep_level()
        score_board.prep_ship()

        # 隐藏光标
        pygame.mouse.set_visible(False)


def check_keyup_events(event, ship):
    """响应松开按键"""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False


def check_keydown_events(event, ai_settings, screen, ship, bullets):
    """响应按下按键"""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_SPACE:
        fire_bullet(ai_settings, screen, ship, bullets)


def update_screen(ai_settings, screen, ship, aliens, bullets, play_button, score_board, stats):
    """重绘屏幕"""
    screen.fill(ai_settings.bg_color)
    for bullet in bullets:
        bullet.draw_bullet()
    ship.blitme()
    aliens.draw(screen)

    if not stats.game_active:
        play_button.draw_button()

    score_board.show_score()
    # 将绘制的屏幕可见
    pygame.display.flip()


def update_bullets(ai_settings, screen, ship, aliens, bullets, stats, score_board, history_record):
    """更新子弹"""
    # 更新子弹位置
    bullets.update()

    # 删除已经消失的子弹
    for bullet in bullets:
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)

    # 如有碰撞 则击杀外星人
    check_alien_bullet_collision(ai_settings, screen, ship, aliens, bullets, stats, score_board, history_record)


def fire_bullet(ai_settings, screen, ship, bullets):
    """开火"""
    if len(bullets) < ai_settings.bullet_allowed:
        new_bullet = Bullet(ai_settings, screen, ship)
        bullets.add(new_bullet)


def get_number_aliens_x(ai_settings, alien_width):
    """计算每行可容纳多少个外星人"""
    available_space_x = ai_settings.screen_width - 2 * alien_width
    number_alien_x = int(available_space_x / (2 * alien_width))
    return number_alien_x


def get_number_rows(ai_settings, ship_height, alien_height):
    """计算屏幕可容纳多少行外星人"""
    available_space_y = (ai_settings.screen_height - (3 * alien_height) - ship_height)
    number_rows = int(available_space_y / (2 * alien_height))
    return number_rows


def create_alien(ai_settings, screen, aliens, alien_number, row_number):
    """创建一个外星人"""
    alien = Alien(ai_settings, screen)
    alien_width = alien.rect.width
    alien.x = alien_width + 2 * alien_width * alien_number
    alien.rect.x = alien.x
    alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
    aliens.add(alien)
    aliens.add(alien)


def create_fleet(ai_settings, screen, ship, aliens):
    """创建外星人群"""
    # 创建一个外星人，并计算每行可容纳多少个外星人
    alien = Alien(ai_settings, screen)
    number_rows = get_number_rows(ai_settings, ship.rect.height, alien.rect.height)
    number_aliens_x = get_number_aliens_x(ai_settings, alien.rect.width)
    # 创建外星人
    for row_number in range(number_rows):
        for alien_number in range(number_aliens_x):
            create_alien(ai_settings, screen, aliens, alien_number, row_number)


def check_fleet_edges(ai_settings, aliens):
    """若有外星人到屏幕边缘则变换方向"""
    for alien in aliens.sprites():
        if alien.check_edges():
            change_fleet_direction(ai_settings, aliens)
            break


def change_fleet_direction(ai_settings, aliens):
    """改变外星人移动方向"""
    for alien in aliens.sprites():
        alien.rect.y += ai_settings.fleet_drop_speed
    ai_settings.fleet_direction *= -1


def update_aliens(ai_settings, ship, aliens, stats, screen, bullets, score_board):
    """更新外星人"""
    check_fleet_edges(ai_settings, aliens)
    aliens.update()

    if pygame.sprite.spritecollideany(ship, aliens):
        hit_ship(ai_settings, stats, screen, ship, aliens, bullets, score_board)

    # 外星人碰到屏幕底部则击中飞船
    check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets, score_board)


def check_alien_bullet_collision(ai_settings, screen, ship, aliens, bullets, stats, score_board, history_record):
    """监测子弹和外星人碰撞"""
    # 判断子弹是否击中外星人，击中则删除子弹及外星人
    collisions = pygame.sprite.groupcollide(bullets, aliens, True, True)

    if collisions:
        for col_aliens in collisions.values():
            stats.score += ai_settings.alien_points * len(col_aliens)
            score_board.prep_score()

        check_high_score(stats, score_board, history_record)

    if len(aliens) == 0:
        bullets.empty()
        create_fleet(ai_settings, screen, ship, aliens)
        ai_settings.increase_speed()

        # 提高等级
        stats.level += 1
        score_board.prep_level()


def hit_ship(ai_settings, stats, screen, ship, aliens, bullets, score_board):
    """外星人击中飞船"""

    if stats.ships_left > 0:
        # 飞船数量-1
        stats.ships_left -= 1

        # 清空外星人和子弹
        aliens.empty()
        bullets.empty()

        score_board.prep_ship()

        # 创建新外星人，并将飞船居中
        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()

        # 暂停1秒
        sleep(1)
    else:
        stats.game_active = False
        pygame.mouse.set_visible(True)


def check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets, score_board):
    """监测外星人是否到屏幕底部"""
    screen_rect = screen.get_rect()
    for alien in aliens.sprites():
        if alien.rect.bottom >= screen_rect.bottom:
            hit_ship(ai_settings, stats, screen, ship, aliens, bullets, score_board)
            break


def check_high_score(stats, score_board, history_record):
    """检查是否诞生了新的最高得分"""
    if stats.score > stats.high_score:
        stats.high_score = stats.score
        history_record.store_high_score(stats.high_score)
        score_board.prep_high_score()
